<?php
class ArticlesController extends AppController {


	var $name = 'Articles';
	var $uses = array('Article', 'Upload');
	//var $helpers = array('Rss');
	var $components = array( 'RequestHandler', 'Email','Security' ); /*'SwiftMailer'*/
	var $paginate = array(
		'limit' => 10,
		'order' => array('Article.created' => 'desc'),
		'conditions' => array('Article.published' => 1)
	);
	var $cacheAction = array(
	    'index'  => 3600,
		'popular' => 3600,
		'latest' => 3600,
		'feed' => 3600,
		'latest_article' => 3600
	);
	
	function beforeFilter() {
		parent::beforeFilter(); 
		
	}
	
	/* Frontend */
	
	function index() {
		//$this->Article->recursive = 0;
		$this->paginate['condition'] = array('Article.published'=>1);
		$this->pageTitle = __('Articles about sourdough baking', true);
		$this->set('articles', $this->paginate());
		//debug($this->Auth);
	}

	function view($slugid = null) {
		if (!$slugid) {
			$this->Session->setFlash(__('Invalid id for Article', true));
			$this->redirect(array('action'=>'index'));
		}
		if(is_numeric($slugid))
			$article = $this->Article->read(null, $slugid);
		else 
			$article = $this->Article->findBySlug($slugid);
		if(!$this->is_admin() and !$article['Article']['published']) {
			$this->Session->setFlash(__('You don\'t have access to this article', true));
			$this->redirect(array('action'=>'index'));
		}
		if(!$this->is_admin()) {
			// Update view count
			$this->Article->id = $article['Article']['id'];
			$current_views = $article['Article']['views']  = $article['Article']['views'] + 1;
			$this->Article->saveField('views', $current_views);
		}
		$this->pageTitle = $article['Article']['title'] . ' / ' . __('Article', true);
		//debug($article);
		$this->set('article', $article);
		$this->set('referer', $this->referer('/articles/', true));
	}
	
	function listview($slugid = null) {
		if ($slugid == null) {
			$this->Session->setFlash(__('Invalid id for Article', true));
			$this->Article->find('all', array());
			$this->redirect(array('action'=>'index'));
		}
		if(is_numeric($slugid))
			$article = $this->Article->read(null, $slugid);
		else 
			$article = $this->Article->findBySlug($slugid);
		if(!$this->is_admin() and !$article['Article']['published']) {
			$this->Session->setFlash(__('You don\'t have access to this article', true));
			$this->redirect(array('action'=>'index'));
		}
		
		$this->set('article', $article);
		//$this->render('listview');
	}
	
	function latest($num = null, $truncate = 25, $offset = 0) {
		$this->pageTitle = $num . __('resent articles', true);
		$params = array(
			'conditions' => $this->paginate['conditions'], //array of conditions
			'recursive' => -1, //int
			'fields' => array('Article.title', 'Article.slug', 'Article.created'), //array of field names
			'order' => $this->paginate['order'], //string or array defining order
			'group' => null, //fields to GROUP BY array('Model.field')
			'limit' => $num,
			'offset' => $offset
		);
		$articles = $this->Article->find('all', $params);
		$this->set('truncate', $truncate);
		$this->set('articles', $articles);
		//if($this->RequestHandler->isAjax()) $this->set('ajax_request', true);
	}
	
	function latest_article() {
		$params = array(
			'conditions' => $this->paginate['conditions'], //array of conditions
			'order' => $this->paginate['order'], //string or array defining order
			'limit' => 1
		);
		$articles = $this->Article->find('all', $params);
		//$this->set('truncate', $truncate);
		//debug($articles);
		$this->set('article', $articles[0]);
		$this->render('listview');
		//if($this->RequestHandler->isAjax()) $this->set('ajax_request', true);
	}
	
	function popular($num = null) {
		$this->pageTitle = $num . __(' most popular articles', true);
		$params = array(
			'conditions' => $this->paginate['conditions'], //array of conditions
			'recursive' => -1, //int
			'fields' => array('Article.title', 'Article.slug', 'Article.created'), //array of field names
			'order' => array('Article.views' => 'asc'), //string or array defining order
			'group' => null, //fields to GROUP BY array('Model.field')
			'limit' => $num
		);
		$articles = $this->Article->find('all', $params);
		$this->set('articles', $articles);
		//$this->render('latest');
		//if($this->RequestHandler->isAjax()) $this->set('ajax_request', true);
	}
	
	function feed() {
		Configure::write ('debug', 0);
		$s = Configure::read('Site');
		$this->RequestHandler->setContent('rss', 'application/xml');
		
		$this->pageTitle = 'Feed test';
		$params = array(
			'conditions' => $this->paginate['conditions'], //array of conditions
			'recursive' => 1, //int
			'fields' => array(), //array of field names
			'order' => $this->paginate['order'], //string or array defining order
			'group' => null, //fields to GROUP BY array('Model.field')
			'limit' => 20,
			'page' => null
		);
		
		$articles = $this->Article->find('all', $params);
		$this->set('channel', array(
			'title' => $s['rss_title'],
			'link' => $s['site_url'],
			'description' => $s['description'],
			'language' => $s['lang']));
		//$this->set('channel', array('title' => $settings['rss_title'], 'description' => $settings['rss_description']));
		$this->set('articles', $articles);
		
	}
	
	/* Uploads functions */
	function admin_addupload() {
		//debug($this);
		
		if (!empty($this->data)) {
			$this->Upload->create();
			$article_id = $this->data['Upload']['article_id'];
			if ($this->Upload->save($this->data)) {
				if($this->RequestHandler->isAjax()) {
					//Configure::write ('debug', 0);
					$this->setAction('viewuploads', $article_id);
				} else {
					$this->Session->setFlash(__('The Upload has been added', true));
					$this->redirect(array('action'=>'edit', 'id' => $article_id));
				}
			} else {
				$this->Session->setFlash(__('The Upload could not be saved. Please, try again.', true));
			}
		}
	}
	
	function admin_viewuploads($article_id=null) {
		if ($article_id != null) {
			
			$article = $this->Article->read(null, $article_id);
			$uploads = $article['Upload'];
		} else {
			$this->Session->setFlash(__('Please supply a Article id.', true));
		}
		$this->set('uploads', $uploads);
	}
	
	function admin_orderupload($upload_id = null, $order = "up") {
		
		$upload = $this->Upload->read(null, $upload_id);
		$article_id = $upload['Upload']['article_id'];
		
		$this->admin_updateorder($article_id);
		
		$article = $this->Article->read(null, $article_id);
		$upload = $this->Upload->read(null, $upload_id);
		$org_order = $upload['Upload']['order'];
		
		
		if($order == "down" and isset($article['Upload'][$org_order+1])) {
			$change_id = $article['Upload'][$org_order+1]['id'];
			$change_order = $article['Upload'][$org_order+1]['order'];
		} 
		if($order == "up" and isset($article['Upload'][$org_order-1])) {
			$change_id = $article['Upload'][$org_order-1]['id'];
			$change_order = $article['Upload'][$org_order-1]['order'];
		}
		$success = true;
		if (isset($change_id)) {
			
			$this->Upload->id = $change_id;
			if(!$this->Upload->saveField('order', $org_order))
				$success = false;
			
			$this->Upload->id = $upload['Upload']['id'];
			if(!$this->Upload->saveField('order', $change_order))
				$success = false;
		}
		if($this->RequestHandler->isAjax()) {
			Configure::write ('debug', 0);
			$this->setAction('admin_viewuploads', $article_id);
		} else {
			if($success)
				$this->Session->setFlash(__('Upload updated successfull!', true));
			else 
				$this->Session->setFlash(__('Error: Upload order not updated!', true));
			$this->redirect(array('action'=>'edit', 'id'=>$article_id));
		}
	}
	function admin_updateorder($id = null) {
		$article = $this->Article->read(null, $id);
		if(isset($article['Upload']) and count($article['Upload'])>0) {
			for($i = 0; $i < count($article['Upload']); $i++) {
				$article['Upload'][$i]['order'] = $i;
			}
			if($this->Article->saveAll($article, array('validate' => false, 'atomic' => false))) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}
	 
	function admin_deleteupload($upload_id = null) {
		if (!$upload_id) {
			$this->Session->setFlash(__('Invalid id for Upload.', true));
			$this->redirect(array('action'=>'index'));
		}
		$tmp_img = $this->Upload->read(null, $upload_id);
		$article_id = $tmp_img['Upload']['article_id'];
		if ($this->Upload->del($upload_id)) {
			if($this->RequestHandler->isAjax()) {
				Configure::write ('debug', 0);
				$this->setAction('admin_viewuploads', $article_id);
			} else {
				$this->Session->setFlash(__('Upload deleted!', true));
				$this->redirect(array('action'=>'edit', 'id'=>$article_id));
			}
		}
	}
	
	function admin_ajax_update($id,$sub){ 
		//Step 1. Update the value in the database
		$value = $this->params['form']['value']; //new value to save 
		$this->Upload->id = $id; 
		if (!$this->Upload->saveField($sub, $value,true)) { // Update the field
			$this->set('error', true); 
		} 
		$contact = $this->Upload->read(array($sub), $id); 
		
		//Step 2. Get the display value for the field if the field is a foreign key
		// See if field to be updated is a foreign key and set the display value
		if (substr($sub,-3) == '_id'){
			// Chop off the "_id"
			$new_sub = substr($sub,0,strlen($sub)-3); 
			// Camelize the result to get the Model name
			$model_name = Inflector::camelize($new_sub);
			// See if the model has a display name other than default "name"; 
			if (!empty($this->$model_name->displayField)) { 
				$display_field = $this->$model_name->displayField;
			} else {
				$display_field = 'title';
			}
			
			// Get the display value for the id
			$value = $this->$model_name->field($display_field,array('id' => $value));
		}
		
		//Step 3. Set the view variable and render the view.
		Configure::write ('debug', 0);
		$this->set('value',trim($value)); 
		$this->beforeRender();
		$this->layout = 'ajax'; 
	}
	

	
	function admin_index() {
		$this->Article->recursive = 0;
		$this->paginate['conditions'] = null;
		$this->set('articles', $this->paginate());
	}

	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Article.', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('article', $this->Article->read(null, $id));
	}
	
	function admin_add() {
		if (!empty($this->data)) {
			$this->Article->create();
			if ($this->Article->save($this->data)) {
				$this->Session->setFlash(__('The Article has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Article could not be saved. Please, try again.', true));
			}
		}
	}
	
	
	function admin_edit($id = null) {
		//debug($this);
		if (empty($this->data)) {
			if($id) {
				// Edit, populate fields
				$this->admin_updateorder($id);
				$this->data = $this->Article->read(null, $id);
				//debug(count($this->data['Upload']));
				//debug("read article");
				
			} else {
				// Add, prefill some fields..
				/*$the_user = $this->Auth->user();
				$this->data['Article']['user_id'] = $the_user['User']['id'];*/
				//debug("prefill");
			}
		} else {
			if($id == null) {
				$this->Article->create();
				//debug("create new article");
			}
			
			if ($this->Article->save($this->data)) {
				$message = __('The Article has been saved', true);
				//debug($this->data);
				if(!empty($this->data['Upload']) and $this->data['Upload']['filename']['tmp_name'] != '') {
					//debug("Creating image");
					$this->Upload->create();
					if($this->data['Upload']['title'] == "")
						$this->data['Upload']['title'] = trim($this->data['Upload']['filename']['name']);
					if($this->Upload->save($this->data['Upload']))
						$message = $message . __(' and the new upload has been saved.', true);
				} else {
					//debug("Not creating image");
					$this->data['Upload'] = null;
				}
				$this->Session->setFlash($message);
				//debug($this->params);
				if(isset($this->params['form']['close'])) {
					$this->redirect(array('action'=>'index'));
				}
				
				if($id == null) {
					$new_id = $this->Article->getInsertID();
					$this->redirect(array('action'=>'edit', $new_id));
				}
						
				$this->data = $this->Article->read(null, $id);	
			} else {
				$this->Session->setFlash(__('The Article could not be saved. Please, try again.', true));
			}
		}
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Article', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Article->del($id)) {
			$this->Session->setFlash(__('Article deleted', true));
			$this->redirect(array('action'=>'index'));
		} else {
			$this->Session->setFlash(__('Article not deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}
	

	
	

}
?>